<?php
/**
 * 官网首页的其他数据
 * Author: lyun
 * Date: 2018/2/23
 * Created by Panxsoft.
 */

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;


use App\Http\Models\Admin\AboutUs;
use App\Http\Models\Admin\ProductCategory;
use App\Http\Models\ArticleTag;
use App\Http\Models\HomepageBanner;
use App\Http\Models\Partner;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;
use Illuminate\Database\Eloquent\Collection;

class HomeController extends Controller
{
    use ApiResponser,
        ApiChecker;

    /**
     * 官网首页
     */
    public function index()
    {
        $banners = (new HomepageBanner)->latest('priority')->latest()->get();
        $partners = (new Partner())->latest('priority')->latest()->get();
        $about_us = (new AboutUs)->latest()->first();
//        $project_cases = (new ArticleTag)->where('super_tag_id', ArticleTag::PROJECT_CASE)
//            ->latest('sort')
//            ->limit(5)
//            ->get();
        $product_categories = (new ProductCategory)->where('super_id', ProductCategory::TOP_CATEGORY)
            ->latest('priority')
            ->limit(5)
            ->with('getSubCategories')
            ->get();

        $product_categories = $this->transformProductCategories($product_categories);

        return view("official_website.home", compact('banners', 'about_us', 'partners', 'product_categories'));
    }

    /**
     * 404
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function errorPage()
    {
        return view("error.404");
    }

    /**
     * @param Collection $product_categories
     * @return Collection
     */
    private function transformProductCategories(Collection $product_categories)
    {
        return $product_categories->transform(function(ProductCategory $product_category){
            if (count($product_category->getSubCategories)) {
                $product_category->id = $product_category->getSubCategories->first()->id;
            }
            $product_category->addHidden('getSubCategories');

            return $product_category;
        });
    }
}
